
package cn.sinobest.pe.cons;

import java.util.Map;

import org.pentaho.di.core.database.Database;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.encryption.Encr;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.repository.IUser;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.repository.RepositorySecurityManager;
import org.pentaho.di.repository.RepositorySecurityProvider;
import org.pentaho.di.repository.UserInfo;
import org.pentaho.di.repository.kdr.KettleDatabaseRepository;
import org.pentaho.di.repository.kdr.KettleDatabaseRepositoryMeta;
import org.pentaho.di.repository.kdr.KettleDatabaseRepositorySecurityProvider;
import org.pentaho.di.repository.kdr.delegates.metastore.KettleDatabaseRepositoryMetaStore;

import cn.sinobest.pe.Excutor;

/**
 * 单例化资源库，应用启动时加载
 * @author wuxinxue
 * @time 2015-6-10 上午8:54:17
 * @copyright hnisi
 */
public class RepositorySingleton {
	
	/**
	 * 资源库连接
	 */
	private static KettleDatabaseRepositoryMeta repositoryMeta = null;
	private static String userName = "admin";
	private static String userPass;
	
	/**
	 * 私有的实例化
	 * @param fileName
	 * @throws KettleException
	 */
	private RepositorySingleton() {
	}
	
	/**
	 * 资源库初始化
	 * @return
	 */
	public static boolean init() {
		String querySql = "SELECT PASSWORD FROM R_USER WHERE \"LOGIN\"='"+ userName +"'";
		Map userInfo = Excutor.dbService.queryForSingle(querySql, null, null);
		userPass = (String) userInfo.get("PASSWORD");
		
		try{
			String driver = Excutor.peConfig.getValue("db_driverClassName");
			String url = Excutor.peConfig.getValue("db_url");
			String user = Excutor.peConfig.getValue("db_username");
			String pass = Excutor.peConfig.getValue("db_password");
			if(driver.equals("dm.jdbc.driver.DmDriver")){//dm database
				String urlInfos = url.substring("jdbc:dm://".length());
				int portIndex = urlInfos.indexOf(":");
				int serverIndex = urlInfos.indexOf("/");
				String dbhost = urlInfos.substring(0, portIndex);
				String port = urlInfos.substring(portIndex+1, serverIndex);
				String db = urlInfos.substring(serverIndex+1);
				
				DatabaseMeta databaseMeta = new DatabaseMeta("Kettle", "ORACLE", "Native", dbhost, db, port, user, pass);
				repositoryMeta = new KettleDatabaseRepositoryMeta("Kettle","Kettle","Kettle",databaseMeta);
			} else {
				int index = url.indexOf("/");
				if(index > 0 ){
					char last = url.charAt(index-1);
					if( last != ':' )	url = url.replaceFirst("/", ":/");
		        }
				String[] urlInfos = url.split(":");
				if(urlInfos==null||urlInfos.length<6){
					System.out.println("repository url is wrong!");
					return false;
				}
				String dbhost = urlInfos[3].substring(1);
				String port = urlInfos[4];
				String db = urlInfos[5];
				
				DatabaseMeta databaseMeta = new DatabaseMeta("Kettle", "ORACLE", "Native", dbhost, db, port, user, pass);
				repositoryMeta = new KettleDatabaseRepositoryMeta("Kettle","Kettle","Kettle",databaseMeta);
			}
			return true;
		} catch (Exception e){
			e.printStackTrace();
			return false;
		}
	}

	
	/**
	 * 获取用户的资源库信息
	 * @param userId
	 * @return
	 * @throws Exception 
	 * @throws Exception 
	 */
	public static Repository getRepository(String jobChannelId) throws Exception {
		KettleDatabaseRepository repository = new KettleDatabaseRepository();
		repository.init(repositoryMeta, jobChannelId);
		Database database = repository.connectionDelegate.getDatabase();
		database.setConnection(Excutor.dbService.getJdbcTemplate().getDataSource().getConnection());
		repository.connectionDelegate.setDatabase(database);
		IUser userinfo = repository.userDelegate.loadUserInfo(new UserInfo(), userName, Encr.decryptPassword(userPass));
		KettleDatabaseRepositorySecurityProvider securityProvider = new KettleDatabaseRepositorySecurityProvider( repository, repositoryMeta, userinfo );
		
		repository.setSecurityProvider(securityProvider);
		repository.registerRepositoryService( RepositorySecurityProvider.class, securityProvider );
		repository.registerRepositoryService( RepositorySecurityManager.class, securityProvider );
		repository.connectionDelegate.closeReadTransaction();
		repository.metaStore = new KettleDatabaseRepositoryMetaStore( repository );
		repository.setConnected(true);
//		repository.init(repositoryMeta);
//		repository.connect(userName, Encr.decryptPassword(userPass));
		return repository;
	}
}
